package com.leetcode;

import com.leetcode.common.TreeNode;

/**
 * 108. 将有序数组转换为二叉搜索树
 * 二分法递归创建左右子树
 * 总是选择中间位置右边的数字作为根节点
 *
 * @author fy
 * @date 2022/4/26 20:13
 */
public class Solution108_2 {

    public TreeNode sortedArrayToBST(int[] nums) {
        return createBST(nums, 0, nums.length - 1);
    }

    private TreeNode createBST(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }
        if (left == right) {
            return new TreeNode(nums[left]);
        }
        // 总是选择中间位置右边的数字作为根节点
        int mid = (left + right + 1) >> 1;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = createBST(nums, left, mid - 1);
        root.right = createBST(nums, mid + 1, right);
        return root;
    }

}
